const http = require('http');
const fs = require('fs');
const path = require('path');

const DATA_FILE = path.join(__dirname, 'data.json');

function ensureDataFile() {
  if (!fs.existsSync(DATA_FILE)) {
    const initial = [
      { username: 'zhangsan', password: '12354' },
      { username: 'lisi', password: '12354' },
      { username: 'wangwu', password: '12354' },
    ];
    fs.writeFileSync(DATA_FILE, JSON.stringify(initial, null, 2), 'utf-8');
  }
}

function readUsers() {
  ensureDataFile();
  const text = fs.readFileSync(DATA_FILE, 'utf-8');
  return JSON.parse(text);
}

function validateUser(username, password) {
  const users = readUsers();
  return users.some((u) => u.username === username && u.password === password);
}

const server = http.createServer((req, res) => {
  if (req.method === 'POST' && req.url === '/login') {
    let body = '';
    req.on('data', (chunk) => (body += chunk));
    req.on('end', () => {
      try {
        const contentType = req.headers['content-type'] || '';
        let payload = {};
        if (contentType.includes('application/json')) {
          payload = JSON.parse(body || '{}');
        } else if (contentType.includes('application/x-www-form-urlencoded')) {
          payload = Object.fromEntries(new URLSearchParams(body));
        }
        const { username, password } = payload;

        if (!username || !password) {
          res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
          res.end('缺少 username 或 password');
          return;
        }

        const ok = validateUser(username, password);
        res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
        res.end(ok ? '登录成功' : '用户名、密码不正确');
      } catch (err) {
        res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
        res.end('服务器错误: ' + err.message);
      }
    });
  } else if (req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
    res.end('POST 到 /login 进行验证');
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
    res.end('Not Found');
  }
});

const PORT = 8081;
server.listen(PORT, () => {
  ensureDataFile();
  console.log(`登录服务已启动: http://localhost:${PORT}`);
});


